package com.ktjy.member.controller;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.poi.excel.ExcelWriter;
import com.ktjy.member.domain.Cart;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ktjy.common.annotation.Log;
import com.ktjy.common.core.controller.BaseController;
import com.ktjy.common.core.domain.AjaxResult;
import com.ktjy.common.enums.BusinessType;
import com.ktjy.member.domain.WxUser;
import com.ktjy.member.service.IWxUserService;
import com.ktjy.common.utils.poi.ExcelUtil;
import com.ktjy.common.core.page.TableDataInfo;

/**
 * 微信小程序端的会员Controller
 *
 * @author ktjy
 * @date 2025-03-17
 */
@RestController
@RequestMapping("/member/user")
public class WxUserController extends BaseController
{
    @Autowired
    private IWxUserService wxUserService;

/**
 * 查询微信小程序端的会员列表
 */
@PreAuthorize("@ss.hasPermi('member:user:list')")
@GetMapping("/list")
    public TableDataInfo list(WxUser wxUser)
    {
        startPage();
        List<WxUser> list = wxUserService.selectWxUserList(wxUser);
        return getDataTable(list);
    }


    /**
     * 导出微信小程序端的会员列表
     */
    @PreAuthorize("@ss.hasPermi('member:user:export')")
    @Log(title = "微信小程序端的会员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WxUser wxUser)
    {

        List<WxUser> list = wxUserService.selectWxUserList(wxUser);

        // 添加序号列
        List<Map<String, Object>> exportList = new ArrayList<>();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < list.size(); i++) {
            WxUser wxUser1 = list.get(i);
            Map<String, Object> exportData = new LinkedHashMap<>();
            exportData.put("index", i + 1); // 序号列的值自增，从1开始
            exportData.put("id", wxUser1.getId());
            exportData.put("userName",wxUser1.getUsername());

            String gender = "男";
            if (wxUser1.getGender() == 1){
                gender = "女";
            } else if (wxUser1.getGender() == 2){
                gender = "未知";
            }
            exportData.put("gender", gender);

            exportData.put("birthday",dateFormat.format(wxUser1.getBirthday()));

            String userLevel = "普通用户";
            if (wxUser1.getUserLevel() == 1){
                userLevel = "VIP用户";
            } else if (wxUser1.getUserLevel() == 2){
                userLevel = "高级VIP用户";
            }
            exportData.put("userLevel", userLevel);


            String enabled = "正常";
            if (wxUser1.getEnabled() == 1){
                enabled = "禁用";
            }

            exportData.put("enabled", enabled);

            // 把exportData这个键值对集合添加到上面定义的exportList集合中
            // 注意看上面定义时是（List<Map<String, Object>>）
            exportList.add(exportData);
        }

        // 在内存操作，写出到浏览器
        ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter(true);
        writer.setOnlyAlias(true); // 设置成只导出有别名的字段
        // 自定义标题别名
//        writer.addHeaderAlias("index", "索引");
        writer.addHeaderAlias("id", "编号");
        writer.addHeaderAlias("userName", "会员名称");
        writer.addHeaderAlias("gender", "性别");
        writer.addHeaderAlias("birthday", "生日");
        writer.addHeaderAlias("userLevel", "会员等级");
        writer.addHeaderAlias("enabled", "状态");

        writer.write(exportList, true);

        // 自动调整列宽
        writer.autoSizeColumnAll();

        // 设置最小列宽
        int minColumnWidth = 20; // 可以根据需要调整最小列宽
        int columnCount = writer.getSheet().getRow(0).getLastCellNum();
        for (int i = 0; i < columnCount; i++) {
            int width = writer.getSheet().getColumnWidth(i);
            if (width < minColumnWidth * 256) {
                writer.getSheet().setColumnWidth(i, minColumnWidth * 256);
            }
        }



        try {
            // 设置浏览器响应的格式
            String fileName = URLEncoder.encode("用户信息", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            out.close();
            writer.close();
        }catch (Exception e){
            System.out.println(e);
        }

    }

    /**
     * 获取微信小程序端的会员详细信息
     */
    @PreAuthorize("@ss.hasPermi('member:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(wxUserService.getById(id));
    }

    /**
     * 新增微信小程序端的会员
     */
    @PreAuthorize("@ss.hasPermi('member:user:add')")
    @Log(title = "微信小程序端的会员", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WxUser wxUser)
    {
        return toAjax(wxUserService.save(wxUser));
    }

    /**
     * 修改微信小程序端的会员
     */
    @PreAuthorize("@ss.hasPermi('member:user:edit')")
    @Log(title = "微信小程序端的会员", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WxUser wxUser)
    {
        return toAjax(wxUserService.updateById(wxUser));
    }

    /**
     * 删除微信小程序端的会员
     */
    @PreAuthorize("@ss.hasPermi('member:user:remove')")
    @Log(title = "微信小程序端的会员", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Integer> ids)
    {
        return toAjax(wxUserService.removeByIds(ids));
    }
}